<template>
  <div>
    <el-dialog :append-to-body="true" title="视频上传" :visible.sync="uploadVisible" :close-on-click-modal="false">
      <el-upload
        class="upload-demo"
        action=""
        ref="upload"
        :file-list="fileList"
        :show-file-list="false"
        multiple
        :http-request="beginUpload"
        :on-change="handleChange"
        :on-remove="handleRemove"
        :auto-upload="false"
        accept=".mp4" 
      > 
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitForm">{{text}}</el-button>
        <i class="el-icon-delete" style="float:right;font-size:20px;margin-top:10px;cursor: pointer;" @click="clear"></i>
        <!-- <el-button size="small" type="primary" style="float:right" @click="clear">清空</el-button> -->
        <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="resumeUpload">继续</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="stopUplosd">暂停</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="abortMultipartUpload">清除切片</el-button> -->
      </el-upload>
      <div class="newFileListCon">
        <div class="newFileListItem" v-for="(item , index) in newFileList" :key="index">
          <div class="newFileList_left">
            <span>{{item.name}}</span>
            <el-progress :percentage="item.percentage" :status="item.uploadStatus"></el-progress>
          </div>
          <div class="newFileList_right" v-if="iconShow">
            <el-button type="text" v-if="item.transcodeUrl" @click="onCopy(item.transcodeUrl)">复制</el-button>
            <el-tooltip class="item" effect="dark" v-if="item.transcodeUrl" content="链接已生成，正在转码中，查询视频是否可以播放请关注视频列表！" placement="top-start">
               <i class="el-icon-warning"></i>
              </el-tooltip>
            <!-- <i class="el-icon-video-play" v-if="item.transcodeUrl" @click="videoPlay(item)"></i> -->
            <i class="el-icon-close" @click="removeItem(index)"></i>
          </div>
        </div>
      </div>
      <div class="videoPLayer" v-if="playerOptions.sources[0].src">
        <div class="player_title">{{videoTitle}}</div>
        <video-player  class="video-player vjs-custom-skin" style="width:100%;" ref="videoPlayer" :playsinline="true" :options="playerOptions"></video-player>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import OSS from 'ali-oss'
import { getOss , videoTranscoding , getVideosList} from '@/api/pubilcClass'
import { mapGetters } from 'vuex'
let pinyin = require('js-pinyin');
export default {
  components: {},
  computed: {},
  props: {
    templateInfo:{
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      uploadVisible: false,
      fileList:[],
      newFileList:[],
      file: null,
      iconShow:true,
      tempCheckpoint: null, // 用来缓存当前切片内容
      uploadId: '',
      uploadStatus: null, // 进度条上传状态
      percentage: 0, // 进度条百分比
      uploadName: '', //Object所在Bucket的完整路径
      text:'点击上传',
      num:0,
      videoTitle:'',
      // 视频播放
      playerOptions : {
        playbackRates: [0.7, 1.0, 1.5, 2.0], //播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: "application/x-mpegURL", // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            src: "" // url地址
          }
        ],
        poster: "", //你的封面地址
        // width: document.documentElement.clientWidth,
        notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true  //全屏按钮
        }
      },
    }
  },
  created() {
    this.getOssDetail()
  },
  mounted() {},
  methods: {
    // 获取oss key sercet
    async getOssDetail(){
      await getOss({}).then(res => {
        console.log('oss',res)
        this.client = new OSS({
          region: 'https://oss-cn-beijing.aliyuncs.com',
          accessKeyId: res.data.accessKeyId,
          accessKeySecret: res.data.accessKeySecret,
          bucket: 'risefu',
          stsToken:res.data.securityToken,
          endpoint: 'https://oss-cn-beijing.aliyuncs.com'
        })
      })
    },
    // 点击上传至服务器
    submitForm(file) {
      this.multipartUpload();
    },
    // 清空
    clear(){
      this.newFileList.map((item ,index) =>{
        this.removeItem(index)
      })
      this.newFileList = []
      this.fileList = []
    },
    // 暂停分片上传。
    stopUplosd () {
      // window.removeEventListener('online', this.resumeUpload) // 暂停时清除时间监听
      let result = client.cancel();
      console.log( result, '---------暂停上传-----------')
    },
    async removeItem(index){
      let current = this.newFileList[index]
      const name = current.uploadName; // Object所在Bucket的完整路径。
      const uploadId = current.upload; // 分片上传uploadId。
      if(name && uploadId && current.percentage!= 100){
        const result = await this.client.abortMultipartUpload(name, uploadId);
        // this.resumeUpload()
      }
      this.newFileList.splice(index , 1)
    },
    // 视频转码
    async videoTranscoding(url,index){
      await videoTranscoding({url:url}).then(res => {
        this.newFileList[index].transcodeUrl = res.data.transcodeUrl
        this.iconShow = false
        this.iconShow = true
        this.$notify({
          title: '成功',
          message: `${this.newFileList[index].name} 视频上传成功`,
          type: 'success'
        });
      })
    },
    async multipartUpload () {
        if (!this.newFileList.length) {
          this.$message.error('请选择文件')
          return
        }
        let _this = this
        try {
          this.newFileList.forEach((item,index)=>{
            item.uploadStatus = null
            item.percentage = 0
            item.transcodeUrl = ''
            console.log('fileName', item)
            let date = new Date()
            let y = date.getFullYear()
            let m = date.getMonth() + 1
            _this.num ++ 
            let timestamp = new Date().getTime() + '' + _this.num
            let name = pinyin.getCamelChars(item.name + '')
            name = name.replace(/[^\x00-\xff]/g , '')
            name = name.replace(/\s+/g,"")  
            let fileName = `video/${y}/${m}/${timestamp}/${name}`
            let result =  _this.client.multipartUpload(fileName, item.raw, {
              headers: {
                'Content-Disposition': 'inline',
                'Content-Type': item.raw.type 
              },
              progress: (p, checkpoint) => {
                item.tempCheckpoint = checkpoint;
                item.upload = checkpoint.uploadId
                console.log(checkpoint.name,checkpoint.uploadId)
                item.uploadName = checkpoint.name
                item.percentage = parseInt(p * 100) 
                if(item.percentage == 100){
                  setTimeout(()=>{
                    let url = `https://cdc-file.risechina.com/${fileName}`
                    this.videoTranscoding(url,index)
                  },1000)
                }
                // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
              },
              meta: { year: 2021, people: 'dev' },
              mime: item.raw.type
            });
              console.log(result, item.raw, 'result= 切片上传完毕=');
          })
          //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
          // let result = await this.client.multipartUpload(fileName, this.file, {
          // headers: {
          //   'Content-Disposition': 'inline',
          //   'Content-Type': this.file.type //注意：根据图片或者文件的后缀来设置，我试验用的‘.png'的图片，具体为什么下文解释
          // },
          // progress: (p, checkpoint) => {
          //     this.tempCheckpoint = checkpoint;
          //     this.upload = checkpoint.uploadId
          //     this.uploadName = checkpoint.name
          //     this.percentage = p * 100
          //     // 断点记录点。浏览器重启后无法直接继续上传，您需要手动触发上传操作。
          //   },
          //   meta: { year: 2021, people: 'dev' },
          //   mime: this.file.type
          // });
          // console.log(result, this.fileList, 'result= 切片上传完毕=');
        } catch (e) {
          // window.addEventListener('online', this.resumeUpload) // 该监听放在断网的异常处理
          // 捕获超时异常。
          if (e.code === 'ConnectionTimeoutError') { // 请求超时异常处理
          // this.uploadStatus = 'exception'
          console.log("TimeoutError");
          // do ConnectionTimeoutError operation
        }
      }
    },
    // 恢复上传。
    async resumeUpload () {
       if (!this.newFileList.length) {
          this.$message.error('请选择文件')
          return
        }

        let _this = this

        try {

          this.newFileList.forEach((item,index)=>{
            item.uploadStatus = null
            item.percentage = 0
            let date = new Date()
            let y = date.getFullYear()
            let m = date.getMonth() + 1
            let timestamp = Date.parse(new Date())
            let name = pinyin.getCamelChars(item.name + '')
            name = name.replace(/[^\x00-\xff]/g , '')
            name = name.replace(' ' , '')
            let fileName = `video/${y}/${m}/${timestamp}/${item.name}`
            let result =  _this.client.multipartUpload(fileName, item.raw, {
              headers: {
                'Content-Disposition': 'inline',
                'Content-Type': item.raw.type //注意：根据图片或者文件的后缀来设置，我试验用的‘.png'的图片，具体为什么下文解释
              },
              progress: (p, checkpoint) => {
                item.tempCheckpoint = checkpoint;
                item.percentage = parseInt(p * 100) 
                console.log('========')
                if(item.percentage == 100){
                  this.$notify({
                    title: '成功',
                    message: `${item.name} 视频上传成功`,
                    type: 'success'
                  });
                }
              },
              checkpoint: item.tempCheckpoint,
              meta: { year: 2021, people: 'dev' },
              mime: item.raw.type
            });
              console.log(result, item.raw, 'result= 切片上传完毕=');
          })

        } catch (e) {
          if (e.code === 'ConnectionTimeoutError') { // 请求超时异常处理
          console.log("TimeoutError");
        }
      }
      // window.removeEventListener('online', this.resumeUpload)
      // if (!this.tempCheckpoint) {
      //   this.$message.error('请先上传')
      //   return
      // }
      // this.uploadStatus = null
      // try {
      // let result = await client.multipartUpload(this.file.name, this.file, {
      //   headers: {
      //     'Content-Disposition': 'inline',
      //     'Content-Type': this.file.type //注意：根据图片或者文件的后缀来设置，我试验用的‘.png'的图片，具体为什么下文解释
      //   },
      //   progress: (p, checkpoint) => {
      //     this.percentage = p * 100
      //     console.log(p, checkpoint, 'checkpoint----恢复上传的切片信息-------')
      //     this.tempCheckpoint = checkpoint;
      //   },
      //   checkpoint: this.tempCheckpoint,
      //   meta: { year: 2020, people: 'dev' },
      //   mime: this.file.type
      // })
      //  console.log(result, 'result-=-=-恢复上传完毕')
      // } catch (e) {
      //  console.log(e, 'e-=-=-');
      // }
    },
    beginUpload (file) {
      this.multipartUpload()
    },
    // 选择文件发生改变
    handleChange(file, fileList) {
      console.log(file)
      file.uploadStatus = null
      file.percentage = 0
      file.tempCheckpoint = null
      file.uploadId = ''
      file.uploadStatus = null
      file.uploadName = ''
      file.transcodeUrl = ''
      this.newFileList.push(file)
    },
     // 复制链接
    onCopy(transcodingUrl) {
      var input = document.createElement("input");   // 直接构建input
      input.value = transcodingUrl;  // 设置内容
      document.body.appendChild(input);    // 添加临时实例
      input.select();   // 选择实例内容
      document.execCommand("Copy");   // 执行复制
      document.body.removeChild(input); // 删除临时实例
      this.$message({
        message: `复制成功！`,
        type: 'success'
      })
    },
    // 播放视频
    videoPlay(item){
      this.videoTitle = item.name
      this.playerOptions.sources[0].src = item.transcodeUrl
    },
    handleRemove(file, fileList) {},
  },
  watch: {
    'uploadVisible': {
      handler(now, old) {
        if(!now){
          this.playerOptions.sources[0].src = ''
          this.videoTitle = ''
        }
          
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep {
  .el-dialog {
    border-radius: 10px!important;
    width: 500px;
  }
  .el-progress{
    width: 200px;
  }
}
.newFileListCon{
  margin-top: 10px;
}
.videoPLayer{
  position: relative;
  .player_title{
    position: absolute;
    top: 10px;
    left: 10px;
    color: #fff;
    z-index: 10000;
  }
}

.newFileListItem{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
  .newFileList_left{
    display: flex;
    flex-direction: row;
    width: 80%;
    span{
      margin-right: 20px;
      width: 250px;
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
      
    }
  }
  .newFileList_right{
    i{
      cursor: pointer;
      font-size: 16px;
      margin-left: 15px;
    }
  }  
}

</style>
